package com.prp.gwt.server;

import com.prp.algorithm.UserValidation;
import com.prp.gwt.client.ClientConstants;
import com.prp.gwt.client.ClientException;
import com.prp.gwt.client.user.profile.ProfileService;
import com.prp.gwt.client.vo.User;

public class ProfileServiceImpl extends GlobalServiceImpl implements
		ProfileService {

	private static final long serialVersionUID = 3592152719167449310L;

	@Override
	public void updateUserInfo(User user) throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		com.prp.bo.User.modifyUserInfo(userId, user);
	}

	@Override
	public boolean modifyPassword(String oldPassword, String newPassword)
			throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if (!com.prp.bo.User.checkPassword(com.prp.bo.User.getUser(userId)
				.getEmail(), oldPassword))
			return false;
		return com.prp.bo.User.modifyPassword(userId, newPassword);
	}

	@Override
	public boolean modifyAddress(String address) throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if(address.length()>30)
			return false;
		return com.prp.bo.User.modifyAddress(userId, address);
	}

	@Override
	public boolean modifyBlog(String blog) throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if(blog.length()>128)
			return false;
		return com.prp.bo.User.modifyBlog(userId, blog);
	}

	@Override
	public boolean modifyIntroduction(String introduction)
			throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if(introduction.length()>800)
			return false;
		return com.prp.bo.User.modifyIntroduction(userId, introduction);
	}

	@Override
	public boolean modifyRealName(String realName) throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if(!realName.isEmpty() && !UserValidation.validateUsername(realName))
			return false;
		return com.prp.bo.User.modifyRealName(userId, realName);
	}

	@Override
	public boolean modifyRegName(String regName) throws ClientException {
		validateAuth(ClientConstants.USER);
		Integer userId = (Integer) getThreadLocalRequest().getSession()
				.getAttribute(ClientConstants.ATTR_USER);
		if(!UserValidation.validateUsername(regName))
			return false;
		return com.prp.bo.User.modifyRegName(userId, regName);
	}

}
